package log;

import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Map;

public class Log {

	private String newline = System.getProperty("line.separator");
	private OutputStreamWriter writer = null;
	private String[] labels = null;
	private int nbrCols = 0;
	private int nbrRows = 0;

	public Log(String fileName) throws IOException {
		this.writer = new FileWriter(fileName);
	}

	public void writeLabels(String[] labels) throws IOException {
		this.nbrCols = labels.length;
		writeData(labels);
		this.labels = labels.clone();
	}

	public void writeData(Map<String, String> data) throws IOException {
		if (data == null) {
			throw new IOException("Null argument");
		}

		String[] row = new String[nbrCols];
		for (int i = 0; i < row.length; i++) {
			if (data.containsKey(labels[i])) {
				row[i] = data.get(labels[i]);
			} else {
				row[i] = "";
			}
		}

		writeData(row);
	}

	public void close() throws IOException {
		if (this.writer != null){
			this.writer.close();
		}
	}
	
	private void writeData(String[] values) throws IOException {

		for (int i = 0; i < values.length; i++) {
			if (i > 0) {
				this.writer.write(",");
			}

			if (values[i] != null) {
				this.writer.write("\"");
				this.writer.write(this.csvValue(values[i]));
				this.writer.write("\"");
			}
		}

		this.writer.write(this.newline);
		this.nbrRows++;
	}

	private String csvValue(String str) {
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);

			sb.append(c);

			switch (c) {

			case '"':
				sb.append('"');
				break;
			}
		}

		return sb.toString();
	}

}
